package com.gitee.helioz.openai.api.endpoint.finetunes;

import com.gitee.helioz.openai.api.OpenAiService;
import com.gitee.helioz.openai.api.dto.DeleteResponse;
import com.gitee.helioz.openai.api.dto.finetune.FineTuneCreateRequest;
import com.gitee.helioz.openai.api.dto.finetune.FineTuneEventsResponse;
import com.gitee.helioz.openai.api.dto.finetune.FineTuneListResponse;
import com.gitee.helioz.openai.api.dto.finetune.FineTuneResponse;
import com.gitee.helioz.openai.common.constants.OpenAiApiUrl;
import com.gitee.helioz.openai.common.util.json.GsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 〈微调服务〉
 *
 * @author <a href="https://gitee.com/helioz">Morning Starr</a>
 */
@Slf4j
@RequiredArgsConstructor
public class FineTuneServiceImpl implements FineTuneService {

    private final OpenAiService openAiService;

    @Override
    public FineTuneResponse create(FineTuneCreateRequest createRequest) {
        String requestJson = GsonUtil.toJson(createRequest);
        String responseStr = openAiService.post(OpenAiApiUrl.FineTunes.CREATE.getUrl(openAiService.getApiHost()), requestJson);
        return GsonUtil.fromJson(responseStr, FineTuneResponse.class);
    }

    @Override
    public FineTuneListResponse list() {
        String responseStr = openAiService.get(OpenAiApiUrl.FineTunes.LIST.getUrl(openAiService.getApiHost()));
        return GsonUtil.fromJson(responseStr, FineTuneListResponse.class);
    }

    @Override
    public FineTuneResponse retrieve(String fineTuneId) {
        String responseStr = openAiService.get(OpenAiApiUrl.FineTunes.RETRIEVE.getUrl(openAiService.getApiHost()) + fineTuneId);
        return GsonUtil.fromJson(responseStr, FineTuneResponse.class);
    }

    @Override
    public FineTuneResponse cancel(String fineTuneId) {
        String responseStr = openAiService.post(String.format(OpenAiApiUrl.FineTunes.CANCEL_FORMAT.getUrl(openAiService.getApiHost()), fineTuneId), "");
        return GsonUtil.fromJson(responseStr, FineTuneResponse.class);
    }

    @Override
    public FineTuneEventsResponse events(String fineTuneId, boolean stream) {
        String url = String.format(OpenAiApiUrl.FineTunes.LIST_EVENTS_FORMAT.getUrl(openAiService.getApiHost()), fineTuneId);
        String responseStr = openAiService.get(url + "?stream=" + stream);
        return GsonUtil.fromJson(responseStr, FineTuneEventsResponse.class);
    }

    @Override
    public DeleteResponse delete(String model) {
        String responseStr = openAiService.get(OpenAiApiUrl.FineTunes.DELETE_MODEL.getUrl(openAiService.getApiHost()) + model);
        return GsonUtil.fromJson(responseStr, DeleteResponse.class);
    }
}
